<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');
/******************************************************************************
 * System           :
 * Sub System       :
 * File Name        : MY_Controller
 * Description      :
 * Version          : 1.0
 *
 *****************************************************************************/

class MY_Controller extends CI_Controller {

	public $UPLOAD_PATH = "./static/upload";

	public function __construct() {
		parent::__construct();
		$this -> load -> library('session');
	}

	public function print_json($data) {
		$this -> output -> set_content_type('application/json') -> set_output(json_encode($data));
	}

	public function login_success($user) {
		$token_key = $this -> createToken("DM", 30);
		$this -> session -> set_userdata($user);
		$this -> session -> set_userdata(array('token_key' => $token_key));
		return $token_key;
	}

	public function check_login_status($username, $token_key) {
		$save_token = $this -> session -> userdata('token_key');
		$save_user = $this -> session -> userdata('username');
		if ($token_key == $save_token && $save_user == $username) {
			return true;
		}
		return false;
	}

	function createToken($tokenprefix, $sectionlength) {
		// Declare salt and prefix
		$token = $tokenprefix;
		$salt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';

		// Prepare randomizer
		srand((double) microtime() * 1000000);

		// Create the token

		for ($n = 0; $n < $sectionlength; $n++) {
			$token .= substr($salt, rand() % strlen($salt), 1);
		}

		// Return the token
		return $token;
	}

	public function postNotification($registration_ids, $data) {
		// Set POST variables
		$url = 'https://android.googleapis.com/gcm/send';
		$GOOGLE_API_KEY = "AIzaSyDVY5nTEprSqHSV8SSpNvu5DJfI2XrBy_s";

		$fields = array('registration_ids' => $registration_ids, 'data' => $data, 'time_to_live' => 600, );

		$headers = array('Authorization: key=' . $GOOGLE_API_KEY, 'Content-Type: application/json');
		// Open connection
		$ch = curl_init();

		// Set the url, number of POST vars, POST data
		curl_setopt($ch, CURLOPT_URL, $url);

		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		// Disabling SSL Certificate support temporarly
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

		// Execute post
		$result = curl_exec($ch);
		if ($result === FALSE) {
			die('Curl failed: ' . curl_error($ch));
		}

		// Close connection
		curl_close($ch);
		// echo $result;
		return $result;
	}

	public function postNotificationiOS($registration_ids, $message) {

		$passphrase = '';
		////////////////////////////////////////////////////////////////////////////////
		$ctx = stream_context_create();
		stream_context_set_option($ctx, 'ssl', 'local_cert', 'dev.pem');
		stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

		// Open a connection to the APNS server
		$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 2, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);

		if (!$fp)
			exit("Failed to connect: $err $errstr" . PHP_EOL);

		//echo 'Connected to APNS' . PHP_EOL;

		// Create the payload body
		$body['aps'] = array('alert' => $message, 'sound' => 'Bark', 'badge' => 23);

		// Encode the payload as JSON
		$payload = json_encode($body);

		// Build the binary notification
		$msg = chr(0) . pack('n', 32) . pack('H*', $registration_ids) . pack('n', strlen($payload)) . $payload;

		// Send it to the server
		$result = fwrite($fp, $msg, strlen($msg));
/*
		if (!$result)
			echo 'Message not delivered' . PHP_EOL;
		else
			echo 'Message successfully delivered' . PHP_EOL;
*/
		// Close the connection to the server
		fclose($fp);
		return $result;
	
	}

	public function uploadImage($base, $path = "") {

		// base64 encoded utf-8 string
		$binary = base64_decode($base);

		// binary, utf-8 bytes
		// header('Content-Type: bitmap; charset=utf-8');

		$save_path = $this -> UPLOAD_PATH . $path;
		if (!is_dir($save_path)) {
			mkdir($save_path, 0777, true);
		}

		$save_path .= '/' . time() . ".jpg";
		$file = fopen($save_path, 'wb');

		fwrite($file, $binary);

		fclose($file);
		return $save_path;
		// echo '<img src=test.jpg>';
	}

}

/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */
